package main

import (
	"bytes"
	"database/sql"
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"path"

	"github.com/Unknwon/com"
	_ "github.com/mattn/go-sqlite3"
	"github.com/mholt/archiver"
	uuid "github.com/satori/go.uuid"
	"smartconn.cc/tosone/ra_main/common"
)

const featuredb = "featuredbinfo.db"
const storydb = "story.db"
const fulldb = "full.db"
const packageFile = "package.json"

func main() {
	var err error
	packageinfo := map[string]string{}
	res, err := ioutil.ReadFile(packageFile)
	checkErr(err)
	json.NewDecoder(bytes.NewReader(res)).Decode(&packageinfo)
	storyName := packageinfo["name"]
	if storyName == "" {
		log.Println("Cannot find name in package.json.")
		return
	}
	storyVersion := packageinfo["version"]
	if storyVersion == "" {
		log.Println("Cannot find version in package.json.")
		return
	}
	storyAuthor := packageinfo["author"]
	tempDir := path.Join(os.TempDir(), uuid.NewV4().String())
	tempDirFull := path.Join(os.TempDir(), uuid.NewV4().String())
	err = os.Mkdir(tempDir, 0755)
	checkErr(err)
	err = os.Mkdir(tempDirFull, 0755)
	checkErr(err)
	if com.IsFile(storydb) {
		os.Remove(storydb)
	}

	db, err := sql.Open("sqlite3", featuredb)
	checkErr(err)
	story, err := sql.Open("sqlite3", storydb)
	checkErr(err)
	full, err := sql.Open("sqlite3", fulldb)
	checkErr(err)

	_, err = full.Exec("CREATE TABLE IF NOT EXISTS \"pages\" (\"PageID\" TEXT, \"num\" INTEGER, \"feature\" TEXT, \"manifest\" TEXT, \"pic\" TEXT)")
	checkErr(err)
	_, err = full.Exec("CREATE TABLE IF NOT EXISTS \"storyInfo\" (\"name\" TEXT, \"author\" INTEGER, \"version\" TEXT, \"date\" TEXT)")
	checkErr(err)
	stmtFullPages, err := full.Prepare("INSERT INTO \"pages\" (\"PageID\", \"num\", \"feature\", \"manifest\", \"pic\") values (?,?,?,?,?)")
	checkErr(err)
	defer stmtFullPages.Close()
	stmtFullInfo, err := full.Prepare("INSERT INTO \"storyInfo\" (\"name\", \"author\", \"version\", \"date\") values (?,?,?,?)")
	checkErr(err)
	defer stmtFullInfo.Close()

	_, err = story.Exec("CREATE TABLE IF NOT EXISTS \"pages\" (\"PageID\" TEXT, \"num\" INTEGER, \"feature\" TEXT, \"manifest\"	TEXT)")
	checkErr(err)
	_, err = story.Exec("CREATE TABLE IF NOT EXISTS \"storyInfo\" (\"name\" TEXT, \"author\" INTEGER, \"version\" TEXT, \"date\" TEXT)")
	checkErr(err)

	stmtStoryPages, err := story.Prepare("INSERT INTO \"pages\" (\"PageID\", \"num\", \"feature\", \"manifest\") values (?,?,?,?)")
	checkErr(err)
	defer stmtStoryPages.Close()
	stmtStoryInfo, err := story.Prepare("INSERT INTO \"storyInfo\" (\"name\", \"author\", \"version\", \"date\") values (?,?,?,?)")
	checkErr(err)
	defer stmtStoryInfo.Close()

	rows, err := db.Query("select * from pages")
	checkErr(err)
	var pagenum string
	var feature string
	for rows.Next() {
		err := rows.Scan(&pagenum, &feature)
		checkErr(err)
		audio := pagenum + ".ogg"
		png := pagenum + ".png"
		if com.IsFile(audio) && com.IsFile(png) {
			err := com.Copy(audio, path.Join(tempDir, audio))
			checkErr(err)
			err = com.Copy(audio, path.Join(tempDirFull, audio))
			checkErr(err)
			err = com.Copy(png, path.Join(tempDirFull, png))
			checkErr(err)
		} else {
			log.Println("Cannot find file: " + audio + " or " + png + ". Please check.")
			return
		}
		uid := uuid.NewV4().String()
		_, err = stmtStoryPages.Exec(uid, pagenum, feature, audio)
		checkErr(err)
		_, err = stmtFullPages.Exec(uid, pagenum, feature, audio, png)
		checkErr(err)
	}
	_, err = stmtFullInfo.Exec(storyName, storyAuthor, storyVersion, common.Now())
	checkErr(err)
	_, err = stmtStoryInfo.Exec(storyName, storyAuthor, storyVersion, common.Now())
	checkErr(err)
	err = com.Copy(storydb, path.Join(tempDir, storydb))
	checkErr(err)
	files, err := ioutil.ReadDir(tempDir)
	checkErr(err)
	absFiles := []string{}
	for _, file := range files {
		if !file.IsDir() {
			absFiles = append(absFiles, file.Name())
		}
	}
	archiver.TarGz.Make("pure-"+storyName+"-"+storyVersion+".tar.gz", absFiles)
	files, err = ioutil.ReadDir(tempDirFull)
	checkErr(err)
	absFiles = []string{}
	for _, file := range files {
		if !file.IsDir() {
			absFiles = append(absFiles, file.Name())
		}
	}
	archiver.TarGz.Make("full-"+storyName+"-"+storyVersion+".tar.gz", absFiles)
}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}
